#import "AuthCodeViewController.h"
#import "PopUIManager.h"
#import "NetWorkManager.h"
#import "EditProfileViewController.h"
#import "JsonUtil.h"

@interface AuthCodeViewController ()
{
    int count_num;
    NSTimer *timer;
}
@property (weak, nonatomic) IBOutlet UILabel *desLabel;

@end

@implementation AuthCodeViewController
@synthesize phoneNumLabel,commitButton,phoneNum,timerTipLabel,validCodeInput;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    
    [self customView];
    count_num=60;
    phoneNumLabel.text = phoneNum;
}

-(void)customView
{
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = @"填写验证码";
    
    phoneNumLabel.textColor = UIColorMake(101, 101, 101);
    timerTipLabel.tintColor = UIColorMake(73, 143, 196);
    
    commitButton.backgroundColor=UIColorMake(252, 74, 74);
    commitButton.layer.cornerRadius = 4.0;
    _desLabel.text =@"";
    _desLabel.textColor = UIColorMake(101, 101, 101);
    NSMutableAttributedString *text =
    [[NSMutableAttributedString alloc]
     initWithString: @"我们已经发送验证码短信到这个号码"];
    
    [text addAttribute:NSForegroundColorAttributeName
                 value:UIColorMake(241, 76, 92)
                 range:NSMakeRange(6, 5)];
    [_desLabel setAttributedText: text];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
}

-(void)timeHandler
{
    if (count_num >=0) {
        timerTipLabel.titleLabel.text = [NSString stringWithFormat:@"短信验证码已发送( %d )",count_num];
        [timerTipLabel setTitle:[NSString stringWithFormat:@"短信验证码已发送( %d )",count_num ] forState:UIControlStateNormal];
        count_num--;
    }else{
        timerTipLabel.titleLabel.text = @"重新获取验证码";
        [timerTipLabel setTitle:@"重新获取验证码" forState:UIControlStateNormal];
    }
}

//重新获取验证码
- (IBAction)reGetAuthCode:(id)sender {
    //当时间小于60的时候，可以再次倒计时获取验证码。
    if (count_num < 0) {
        count_num = 60;
        //此处的superFlag置为-1,为的是请求服务器后不再次进入当前viewController。
        NSString *dataString = [JsonUtil convertDictionaryToJson:[[NSDictionary alloc]initWithObjectsAndKeys:@(1), @"type", phoneNum, @"account", @(1), @"codetype", nil]];
        
        PopUIManager *popUIMgr = [PopUIManager getInstanse];
        [popUIMgr showWaitingUI:self.view];
        
        [[NetWorkManager getInstanse] requestURLAsynMessage:USER_GET_AUTH_CODE data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError) { //连接失败
                NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
                NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
                [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
            }else{//连接成功，判断是否有数据返回
                if (data) {
                    NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                    NSLog(@"数据字典: %@", dict);
                    
                    if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                        //登录失败，弹窗提示
                        NSString *ret_msg;
                        switch ([[dict objectForKey:@"retCode"] integerValue]) {
                            case 10007:{
                                ret_msg= @"该手机号已经注册过";
                                break;
                            }case 1:{
                                ret_msg= @"手机号格式错误";
                                break;
                            }case 3:{
                                ret_msg= @"Success";
                                break;
                            }case 4:{
                                ret_msg= @"数据库操作异常，请稍后再试";
                                break;
                            }default:{
                                ret_msg= @"未知错误";
                                break;
                            }
                        }
                        if (![ret_msg isEqual:@"Success"]) {
                            [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                            
                            return;
                        }else{
                            [popUIMgr popAlertView:nil title:@"提示" message:@"发送成功" cancelButtonTitle:@"确定"];
                        }
                        [popUIMgr removeWaitingUI];
                    }else{
                        [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
                }
            }
            [popUIMgr removeWaitingUI];
        }];

    }else{
        debugLog(@"还未过期");
    }
    
}


- (IBAction)commitCallback{
    
    if (validCodeInput.text.length == 0) {
        [[PopUIManager getInstanse]popAlertView:self title:@"提示" message:@"请输入验证码" cancelButtonTitle:@"确定"];
        return;
    }
    //验证码发送服务器，进行验证
    NSString *dataString = [JsonUtil convertDictionaryToJson:[[NSDictionary alloc]initWithObjectsAndKeys:@"1", @"type", validCodeInput.text, @"authcode", phoneNum, @"account", nil]];
    
    NSString *msg = @"USER_CHECK_REGISTER_AUTHCODE";
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:msg data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) { //连接失败
            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                NSLog(@"数据字典: %@", dict);
                
                if ([[dict objectForKey:@"ret"] integerValue]== 1) {
                    //登录失败，弹窗提示
                    NSString *ret_msg;
                    switch ([[dict objectForKey:@"retCode"] integerValue]) {
                        case 10007:{
                            ret_msg= @"该手机号已经注册过";
                            break;
                        }case 10003:{
                            ret_msg= @"验证码错误";
                            break;
                        }case 10006:{
                            ret_msg= @"手机号格式错误";
                            break;
                        }case 10004:{
                            ret_msg= @"验证码失效";
                            break;
                        }case 1001:{
                            ret_msg= @"用户类型错误";
                            break;
                        }case 1:{
                            ret_msg= @"Success";
                            break;
                        }default:{
                            ret_msg= @"未知错误";
                            break;
                        }
                    }
                    if (![ret_msg isEqual:@"Success"]) {
                        [popUIMgr popAlertView:nil title:@"提示" message:ret_msg cancelButtonTitle:@"确定"];
                        [popUIMgr removeWaitingUI];
                        return;
                    }else{
                        EditProfileViewController *epViewController = [[EditProfileViewController alloc] init];
                        epViewController.phoneNumber = phoneNum;
                        [self.navigationController pushViewController:epViewController animated:YES];
                       
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        [popUIMgr removeWaitingUI];
    }];

    
   // self.navigationController.viewControllers =nil;
    /*
    EditProfileViewController *controller = [[EditProfileViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    window.rootViewController = nav;
     */
    
    //[self.navigationController pushViewController:controller animated:YES];
}

-(void)viewDidDisappear:(BOOL)animated
{
    //停下timer
    [timer invalidate];
}

-(void)viewDidAppear:(BOOL)animated{
    NSLog(@"did appear.");
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeHandler) userInfo:nil repeats:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
